package org.dallasrowing.model.dao;

import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.dallasrowing.model.dao.sqlmap.SqlMapDaoFactory;
import org.hsqldb.jdbcDriver;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

import com.ibatis.common.jdbc.ScriptRunner;

public class DaoTestBase {

	private static final String TEST_SCRIPT = "/test-tables.sql";

	@BeforeClass
	public static void registerDriver() throws Exception 
	{
		DriverManager.registerDriver( new jdbcDriver() );
	}

	@AfterClass
	public static void deregisterDriver() throws Exception 
	{
		DriverManager.deregisterDriver( new jdbcDriver() );
	}

	private Connection connection;

	public DaoTestBase() {
		super();
	}

	@Before
	public void initializeTables() throws Exception 
	{
		connection = DriverManager.getConnection( "jdbc:hsqldb:mem:aname", "sa", "" );

		ScriptRunner runner = new ScriptRunner(connection, false, true);
		runner.runScript( new InputStreamReader( getClass().getResourceAsStream(TEST_SCRIPT) ) );
		connection.close();
	}

	@After
	public void removeConnection() throws Exception 
	{
		getConnection().close();
	}

	protected Connection getConnection() {
		return connection;
	}

	private Properties createHsqlProperties() {
		Properties props = new Properties();
		props.put( "driver", "org.hsqldb.jdbcDriver");
		props.put( "url", "jdbc:hsqldb:mem:aname");
		props.put( "username", "sa");
		props.put( "password", "");
		
		return props;
	}

	protected void initializeHsqlTestDB() {
		SqlMapDaoFactory.instance().initialize( createHsqlProperties() );
	}

}